package org.rency.common.utils.security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.digest.DigestUtils;
import org.rency.common.utils.domain.SYSDICT;
import org.rency.common.utils.exception.CoreException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SHAUtils {

	private static final Logger logger = LoggerFactory.getLogger(SHAUtils.class);

    /**
     * SHA加密
     * @param key
     * @return
     * @throws CoreException
     */
	public static String SHA(String key) {
		try {
			MessageDigest sha = MessageDigest.getInstance("SHA");
			sha.update(key.getBytes());
			return  MD5Utils.bufferToHex(sha.digest()).toUpperCase();
		} catch (NoSuchAlgorithmException e) {
			logger.error("SHA加密异常.",e);
			return null;
		}
	}
	
	/**
	 * SHA-1加密
	 * @param key
	 * @return
	 * @throws CoreException
	 */
	public static String SHA1(String key){
		try {
			return  DigestUtils.sha1Hex(key.getBytes(SYSDICT.CHARSET));
		} catch (UnsupportedEncodingException e) {
			logger.error("SHA-1加密异常.",e);
			return null;
		}
	}
	
	/**
	 * SHA-256加密
	 * @param key
	 * @return
	 * @throws CoreException
	 */
	public static String SHA256(String key){
		try {
			return  DigestUtils.sha256Hex(key.getBytes(SYSDICT.CHARSET));
		} catch (UnsupportedEncodingException e) {
			logger.error("SHA-256加密异常.",e);
			return null;
		}
	}
	
	public static void main(String[] args) throws CoreException {
		System.out.println("SHA="+SHA("rency"));
		System.out.println("SHA1="+SHA1("rency"));
		System.out.println("SHA256="+SHA256("1234562015"));
	}
	
}